<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/12/15
 * Time: 15:48
 */
namespace App\Service\Admin;

use App\Http\Model\MongoDB\LiveList;
use App\Http\Model\Mysql\AnchorModel;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use Carbon\Carbon;
use Illuminate\Support\Facades\Config;

class CloudService extends BaseService
{
    /**
     * 创建直播间
     * @param array $params
     * @return array
     */
    public function createCloud(array $params)
    {
        //rtmp://rtmp.wanghongcheng.cn/live/101
        $max_id     =   LiveList::query()->max('Id');
        $live_id    =   $max_id + 1;
        $host_info  =   AnchorModel::where(['id' => $params['host_id'], 'is_delete' => 0])->select(['id', 'unique_id', 'nick_name'])->first();
        $live['CompanyId']  =   '621b9cc5-11b3-4d0e-ad82-981351e25336';
        $live['AppId']      =   '530defda-cb12-4d24-b0e8-dbfabb76393b';
        $live['HostId']     =   $host_info['unique_id'] ?? 0;
        $live['HostName']   =   $host_info['nick_name'] ?? '';
        $live['CreatedBy']  =   request()->post('admin_info')['user_id'] ?? 0;
        $live['Id']         =   $live_id;
        $live['_id']        =   $live_id;
        $live['Title']      =   $params['live_title'];
        $live['DuringTime'] =   0;
        $live['GoodsNum']   =   0;
        $live['PushUrl']    =   'rtmp://push.wanghongcheng.cn/live/' . $live_id;
        $live['PushAddress']=   'rtmp://push.wanghongcheng.cn/live/';
        $live['PushAuth']   =   $live_id;
        $live['Subscription']=  0;
        $live['ActualSubscription']=  0;
        $live['RTMPPullUrl']=  'rtmp://live.wanghongcheng.cn/live/' . $live_id;
        $live['FLVPullUrl'] =  'http://live.wanghongcheng.com/live/' . $live_id . '.flv';
        $live['HLSPullUrl'] =  'http://live.wanghongcheng.com/live/' . $live_id .'.m3u8';
        $live['AppName']    =  'live';
        $live['StreamName'] =  $live_id;
        $live['MainImg']    =  $params['main_img'];
        $live['StartTime']  =  0;
        $live['EndTime']    =  0;
        $live['Viewers']    =  0;
        $live['ActualViewers']  =  0;
//        $live['ProductIds']     =  '';
//        $live['VideoClips']     =  '';
        $live['Status']         =  0;
        $live['PubStatus']      =  LiveList::NORMAL_PUB;
        $live['StreamStatus']   =  0;
        $live['LastStreamUpdateTime']     =  Carbon::now()->toDateTimeString();
        $live['Desc']     =  $params['live_desc'];
        $live['Subscribed']     =  false;
//        $live['Statistics']     =  '';
//        $live['Tasks']          =  '';
        $live['PlanedStartTime']=  Carbon::parse($params['start_time'])->timestamp;
        $live['PlanedEndTime']  =  Carbon::parse($params['end_time'])->timestamp;
        $result     =   LiveList::create($live);
        if ($result) {
            $this->notifyCloud();
            return [true, '创建成功'];
        } else{
            return [false, '创建失败'];
        }
    }

    /**
     * 直播间地址通知
     * @return array
     * @throws ClientException
     */
    public function notifyCloud()
    {
        $wechat =   Config::get('upload');
        AlibabaCloud::accessKeyClient($wechat['ali_oss']['access_key_id'], $wechat['ali_oss']['access_key_secret'])->regionId('cn-hangzhou')->asDefaultClient();
        try {
            $result =   AlibabaCloud::rpc()->product('live')->scheme('https')->action('AddLiveRecordNotifyConfig')->version('2016-11-01')           // https | http
                        ->method('POST')->host('live.aliyuncs.com')->options([
                            'query' => [
                                'RegionId'  =>  'cn-hangzhou',
                                'DomainName'=>  'live.wanghongcheng.cn',
                                'NotifyUrl' =>  'https://xcxapi.hzwhc.com/api/notify/live',
                                'Format'    =>  'JSON'
                            ],
                        ])->request();
            $result =   $result->toArray();
            if ($result['Code'] == 'OK') {
                return [true, $result['RequestId']];
            } else {
                return [false, '请求失败'];
            }
        } catch (ClientException $exception) {
            return [false, $exception->getMessage()];
        } catch (ServerException $exception) {
            return [false, $exception->getMessage()];
        }
    }
}
